/*
 * Copyright 2020 edenrun.cn All right reserved. This software is the
 * confidential and proprietary information ofedenrun.cn ("Confidential
 * Information"). You shall not disclose such Confidential Information and shall
 * use it only in accordance with the terms of the license agreement you entered
 * into with edenrun.cn.
 */

package com.zoom.pluto.common.util;

import com.alibaba.fastjson.JSON;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.httpclient.HttpStatus;
import org.apache.http.auth.AuthScope;
import org.apache.http.auth.UsernamePasswordCredentials;
import org.apache.http.client.CredentialsProvider;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.utils.URIBuilder;
import org.apache.http.conn.ssl.NoopHostnameVerifier;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.conn.ssl.TrustStrategy;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.BasicCredentialsProvider;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.ssl.SSLContextBuilder;
import org.apache.http.util.EntityUtils;

import javax.net.ssl.SSLContext;
import java.io.IOException;
import java.net.URI;
import java.nio.charset.StandardCharsets;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import java.util.Map;

/**
 * HttpClient工具类
 *
 * @author zoom
 * @date 2020-06-08
 */
@Slf4j
public class HttpClientUtils {

    /**
     * HttpClient 发送Get 请求
     *
     * @param url   Get请求地址
     * @param param 请求参数
     * @return Get 响应
     */
    public static String doGet(String url, Map<String, String> param) {
        // 创建Httpclient对象
        CloseableHttpClient httpclient = createIgnoreSSLHttpClient(null);

        String resultString = "";
        CloseableHttpResponse response = null;
        try {
            // 创建uri
            URIBuilder builder = new URIBuilder(url);
            if(param != null) {
                for(String key : param.keySet()) {
                    builder.addParameter(key, param.get(key));
                }
            }
            URI uri = builder.build();
            // 创建http GET请求
            HttpGet httpGet = new HttpGet(uri);
            RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(2000).setConnectionRequestTimeout(1000).setSocketTimeout(2000).build();
            httpGet.setConfig(requestConfig);
            // 执行请求
            response = httpclient.execute(httpGet);
            // 判断返回状态是否为200
            if(response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
                resultString = EntityUtils.toString(response.getEntity(), "UTF-8");
            }
        } catch(Exception e) {
            log.warn("do get occur exception", e);
        } finally {
            try {
                if(response != null) {
                    response.close();
                }
                httpclient.close();
            } catch(IOException e) {
                e.printStackTrace();
            }
        }
        return resultString;
    }

    /**
     * HttpClient 发送Get 请求
     *
     * @param url   Get请求地址
     * @param param 请求参数
     * @return Get 响应
     */
    public static String doGetWithAuth(String url, Map<String, String> param, String userName, String password) {
        // 创建Httpclient对象
        UsernamePasswordCredentials credentials = new UsernamePasswordCredentials(userName, password);
        CloseableHttpClient httpclient = createIgnoreSSLHttpClient(credentials);

        String resultString = "";
        CloseableHttpResponse response = null;
        try {
            // 创建uri
            URIBuilder builder = new URIBuilder(url);
            if(param != null) {
                for(String key : param.keySet()) {
                    builder.addParameter(key, param.get(key));
                }
            }
            URI uri = builder.build();

            // 创建http GET请求
            HttpGet httpGet = new HttpGet(uri);
            // 执行请求
            response = httpclient.execute(httpGet);
            // 判断返回状态是否为200
            if(response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
                resultString = EntityUtils.toString(response.getEntity(), "UTF-8");
            }
        } catch(Exception e) {
            log.warn("do get occur exception", e);
        } finally {
            try {
                if(response != null) {
                    response.close();
                }
                httpclient.close();
            } catch(IOException e) {
                e.printStackTrace();
            }
        }
        return resultString;
    }

    /**
     * HttpClient 发送Post 请求
     *
     * @param url  请求地址
     * @param json 请求参数
     * @return 响应
     */
    public static String doPostJson(String url, String json) {
        // 创建Httpclient对象
        CloseableHttpClient httpClient = createIgnoreSSLHttpClient(null);
        CloseableHttpResponse response = null;
        String resultString = "";
        try {
            // 创建Http Post请求
            HttpPost httpPost = new HttpPost(url);
            // 创建请求内容
            StringEntity entity = new StringEntity(json, ContentType.APPLICATION_JSON);
            httpPost.setEntity(entity);
            // 执行http请求
            response = httpClient.execute(httpPost);
            log.info("response:{}", JSON.toJSONString(response));
            resultString = EntityUtils.toString(response.getEntity(), StandardCharsets.UTF_8);
        } catch(Exception e) {
            log.error("Call Httpclient Post Method failed", e);
        } finally {
            try {
                if(null != response) {
                    response.close();
                }
            } catch(IOException e) {
                log.warn("close post response occur exception", e);
            }
        }
        return resultString;
    }

    /**
     * HttpClient 发送Post 请求
     *
     * @param url  请求地址
     * @param json 请求参数
     * @return 响应
     */
    public static String doPostJsonWithAuth(String url, String json, String userName, String password) {
        // 创建Httpclient对象
        UsernamePasswordCredentials credentials = new UsernamePasswordCredentials(userName, password);
        CloseableHttpClient httpClient = createIgnoreSSLHttpClient(credentials);
        CloseableHttpResponse response = null;
        String resultString = "";
        try {
            // 创建Http Post请求
            HttpPost httpPost = new HttpPost(url);
            // 创建请求内容
            StringEntity entity = new StringEntity(json, ContentType.APPLICATION_JSON);
            httpPost.setEntity(entity);
            // 执行http请求
            response = httpClient.execute(httpPost);
            log.info("response:{}", JSON.toJSONString(response));
            resultString = EntityUtils.toString(response.getEntity(), StandardCharsets.UTF_8);
        } catch(Exception e) {
            log.error("Call Httpclient Post Method failed", e);
        } finally {
            try {
                if(null != response) {
                    response.close();
                }
            } catch(IOException e) {
                log.warn("close post response occur exception", e);
            }
        }
        return resultString;
    }

    /**
     * 构造忽略SSL证书的HttpClient
     *
     * @param usernamePasswordCredentials 认证信息
     * @return CloseableHttpClient
     */
    public static CloseableHttpClient createIgnoreSSLHttpClient(UsernamePasswordCredentials usernamePasswordCredentials) {
        try {
            SSLContext sslContext = new SSLContextBuilder().loadTrustMaterial(null, new TrustStrategy() {
                public boolean isTrusted(X509Certificate[] chain, String authType) throws CertificateException {
                    return true;
                }
            }).build();
            SSLConnectionSocketFactory sslConnectionSocketFactory = new SSLConnectionSocketFactory(sslContext, NoopHostnameVerifier.INSTANCE);
            if(null == usernamePasswordCredentials) {
                return HttpClients.custom().setSSLSocketFactory(sslConnectionSocketFactory).build();
            } else {
                CredentialsProvider provider = new BasicCredentialsProvider();
                provider.setCredentials(AuthScope.ANY, usernamePasswordCredentials);
                return HttpClients.custom().setSSLSocketFactory(sslConnectionSocketFactory).setDefaultCredentialsProvider(provider).build();
            }
        } catch(Exception e) {
            log.error("error create ignore ssl client", e);
        }
        return null;
    }

}
